package order

import (
	"context"
	"errors"
	"group-buy/group_buy/internal/models"
	"strconv"
	"strings"
	"time"

	"group-buy/group_buy/internal/svc"
	"group-buy/group_buy/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type WriteOffLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewWriteOffLogic(ctx context.Context, svcCtx *svc.ServiceContext) *WriteOffLogic {
	return &WriteOffLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *WriteOffLogic) WriteOff(req *types.WriteOffReq) (resp *types.Order, err error) {
	order := &models.Order{Id: req.OrderId}

	get, err := l.svcCtx.Engine.Get(order)
	if err != nil {
		return nil, err
	}
	if !get {
		return nil, errors.New("获取订单失败")
	}
	if order.Status == 1 {
		return nil, errors.New("订单未完成支付，请支付后核销")
	}
	if order.FinishCount >= order.WriteOffCount {
		return nil, errors.New("订单已达到最大核销次数")
	}
	product := &models.Product{Id: order.ProductId}
	get, err = l.svcCtx.Engine.Get(product)
	if err != nil {
		return nil, err
	}
	if !get {
		return nil, errors.New("获取产品失败")
	}
	user := &models.Member{Id: req.UserId}
	get, err = l.svcCtx.Engine.Get(user)
	if err != nil {
		return nil, err
	}
	if !get {
		return nil, errors.New("获取核销人失败")
	}
	writeOffLi := strings.Split(product.WriteOffUserId, ",")
	isWrite := false
	for i, _ := range writeOffLi {
		if writeOffLi[i] == strconv.FormatInt(req.UserId, 10) {
			isWrite = true
			break
		}
	}
	if !isWrite {
		return nil, errors.New("您不是该产品核销员，无法核销")
	}

	m := &models.WriteOffRecord{
		Id:               0,
		OrderId:          order.Id,
		UserId:           order.UserId,
		ProductId:        order.ProductId,
		BusinessId:       order.BusinessId,
		ProductName:      order.ProductName,
		ProductCover:     order.ProductCover,
		UserName:         order.UserName,
		WriteOffUserId:   user.Id,
		WriteOffUserName: user.Name,
		WriteOffTime:     time.Now().Format(time.DateTime),
	}

	_, err = l.svcCtx.Engine.Insert(m)
	if err != nil {
		return nil, err
	}
	order.FinishCount += 1
	order.Status = 3
	if order.FinishCount >= order.WriteOffCount {
		order.Status = 4
	}
	_, err = l.svcCtx.Engine.ID(order.Id).Update(order)
	if err != nil {
		return nil, err
	}
	statusStr := ""
	switch order.Status {
	case 1:
		statusStr = "未支付"
	case 2:
		statusStr = "已支付"
	case 3:
		statusStr = "待核销"
	case 4:
		statusStr = "已完成"
	}

	return &types.Order{
		Id:            order.Id,
		Code:          order.Code,
		UserId:        order.UserId,
		ProductId:     order.ProductId,
		Amount:        order.Amount,
		UserName:      order.UserName,
		ProductName:   order.ProductName,
		WriteOffCount: order.WriteOffCount,
		FinishCount:   order.FinishCount,
		Status:        order.Status,
		PayOrderId:    order.PayOrderId,
		OpenId:        order.OpenId,
		InviteId:      order.InviteId,
		ProductCover:  order.ProductCover,
		StatusStr:     statusStr,
	}, nil
}
